default_encoding = 'utf-8'
# coding: utf-8
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from rest_framework.decorators import api_view
import json
from myblog.models import DolphinTestRequestTestCase, DolphinTestRequest, DolphinTestProject, DolphinTestGrouping, \
    DolphinTestDatabase, DolphinTestHeards
from myblog.dolphinService.baseCode import getResonCode
from myblog.dolphinService.dolphinJOBService.dolphinImplementCase import ExecutionCase
from myblog.dolphinService.dolphinJOBService.dolphinProcessingData import ModelData
from django.core import serializers
import re
import logging
import math
logger = logging.getLogger('log')
from django.db.models import Q,F

@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def addCase(request):  # 新增测试用例
    data1 = json.loads(request.body)
    data = data1["dynamicValidateForm"]
    myCase_id = data1["myCase_id"]
    try:
        case_name = data["case_name"]  # 用例名称
        case_request_id = data["request_id"]  # 关联接口ID
        request_header_param = data["headers"]  # 当前接口的内容
        headerData = data["headerData"]  # herder前置内容选择内容
        request_data_content = data["domains"]  # 请求接口的参数内容
        request_other_type = data["request_other_type"]  # 是否使用关联其他接口
        request_relation_content = data["request_relation_content"]  # 关联接口内容
        request_result = data["request_result"]  # 断言内容
        otherCaseid = data["caseid"]  # 关联其他用例ID
        otherCaseidConclusionValue = data["caseidConclusionValue"]  # 关联其他用例取值
        dataType = data["dataType"]  # 接口请求json|data
        sqlContent = {
            "sqlTrueFlasetype": data["sqlTrueFlasetype"],
            "sqlChoice": data["sqlChoice"],
            "SQLinput": data["SQLinput"],
            "SQLMomentum": data["SQLMomentum"],
            "sqlClusionValue": data["sqlClusionValue"],
            "sqlTrueFlasetypeLast": data["sqlTrueFlasetypeLast"],
            "sqlChoiceLast": data["sqlChoiceLast"],
            "SQLinputLast": data["SQLinputLast"],
            "SQLMomentumLast": data["SQLMomentumLast"],
            "sqlClusionValueLast": data["sqlClusionValueLast"]
        }
        if myCase_id == "":
            case = DolphinTestRequestTestCase(case_name=case_name,
                                              case_request_id=case_request_id,
                                              request_header_param=request_header_param,
                                              headerData=headerData,
                                              request_data_content=request_data_content,
                                              request_other_type=request_other_type,
                                              request_relation_content=request_relation_content,
                                              request_result=request_result,
                                              otherCaseid=otherCaseid,
                                              otherCaseidConclusionValue=otherCaseidConclusionValue,
                                              dataType=dataType,
                                              sqlContent=sqlContent,
                                              )

        else:
            case = DolphinTestRequestTestCase.objects.get(case_id=int(myCase_id))
            case.case_name = case_name
            case.case_request_id = case_request_id
            case.request_header_param = request_header_param
            case.headerData = headerData
            case.request_data_content = request_data_content
            case.request_other_type = request_other_type
            case.request_relation_content = request_relation_content
            case.request_result = request_result
            case.otherCaseid = otherCaseid
            case.otherCaseidConclusionValue = otherCaseidConclusionValue
            case.dataType = dataType
            case.sqlContent = sqlContent
        case.save()
        response = getResonCode().getSuccess()
        return JsonResponse(response)

    except  EOFError as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)


@csrf_exempt
@api_view(['POST'])
def getCase(request):  # 获取测试用例列表
    data = eval(json.loads(request.body)["data"])
    pageSize=data["pageSize"]
    pageNum=data["pageNum"]
    try:
        caseList = DolphinTestRequestTestCase.objects.filter(case_request_id=data["requestID"]).order_by("-updata_time")
        caseList = caseList.filter(Q(case_name__icontains=data["case_name"]) & Q(request_code__icontains=data["request_code"]))
        gourpSizeList = caseList[:pageSize*pageNum]#查询数据
        gourpCount = caseList.count()#查询总数
        countNum=math.ceil(gourpCount/pageSize)#总页数
        data = json.loads(serializers.serialize("json", gourpSizeList))[pageSize*pageNum-pageSize:pageSize*pageNum]
        for i in range(len(data)):
            creatTime=data[i]["fields"]["creat_time"]
            updata_time = data[i]["fields"]["updata_time"]
            data[i]["fields"]["creat_time"]=re.split('[TZ.]',creatTime)[0]+" "+re.split('[TZ.]',creatTime)[1]
            data[i]["fields"]["updata_time"] = re.split('[TZ.]',updata_time)[0]+" "+re.split('[TZ.]',updata_time)[1]
        response = getResonCode().getSuccess()
        response["data"] = data
        response["countNum"] = countNum #总页数
        response["gourpCount"] = gourpCount #总数据量
        response["pageNum"] = pageNum#当前页码
        response["pageSize"] = pageSize#当前一页多少个数据
        return JsonResponse(response)
    except EOFError as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)



@csrf_exempt
@api_view(['POST'])
def getOneCase(request):  # 获取单个测试用例信息
    data = json.loads(request.body)
    try:
        case = DolphinTestRequestTestCase.objects.filter(case_id=data["case_id"])
        sqllist = ModelData().dataBaseHandle(case.values()[0])
        response = getResonCode().getSuccess()
        response["dynamicValidateForm"] = sqllist
        return JsonResponse(response)
    except  EOFError as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)


# DolphinTestGrouping.objects.filter(group_id=data["id"]).update(group_name = data["name"], remark = data["remark"]) #

@csrf_exempt
@api_view(['POST'])
def deleteCase(request):  # 删除用例信息
    data = eval(json.loads(request.body)["data"])
    try:
        if data["id"] != "":
            DolphinTestRequestTestCase.objects.filter(case_id=data["id"]).delete()
            response = getResonCode().getSuccess()
            response["msg"] = "删除成功"
            return JsonResponse(response)
        else:
            response = getResonCode().getFail()
            response["msg"] = "缺少参数,或参数为空"
            return JsonResponse(response)
    except  EOFError as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)

@csrf_exempt
@api_view(['POST'])
def getAllCass(request):  # 获取关联测试用例
    data = json.loads(request.body)
    try:
        response = getResonCode().getSuccess()
        project_request_list = json.loads(serializers.serialize("json", DolphinTestProject.objects.all()))
        response["project_request_list"] = project_request_list
        gerouplist =  json.loads(serializers.serialize("json", DolphinTestGrouping.objects.filter(group_pj_id=data["pro_id"])))
        response["gerouplist"] = gerouplist
        requstlist = json.loads(serializers.serialize("json", DolphinTestRequest.objects.filter(request_group_id=data["groupid"])))
        response["requstlist"] = requstlist
        caselist = json.loads(serializers.serialize("json", DolphinTestRequestTestCase.objects.filter(case_request_id=data["requestid"])))
        response["caselist"] = caselist
        return JsonResponse(response)

    except EOFError as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)


from myblog.dolphinService.dolphinJOBService.dolphinProvideMethod import method


@csrf_exempt
@api_view(['POST'])
def checkPoint(request):  # 设置检查点
    data = eval(json.loads(request.body)["data"])
    herderList = json.loads(request.body)["herderList"]
    for i in range(len(data)):
        data[i]["herderList"] = herderList
    try:
        logger.info("请求接口参数：%s" % (data))
        Result = method().JOBcheckPoint(data)
        response = getResonCode().getSuccess()
        response["data"] = Result["data"]
        response["reuslt"] = Result["reuslt"]
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)

@csrf_exempt
@api_view(['POST'])
def checkCase(request):  # 检查用例
    data = json.loads(request.body)
    try:
        logger.info("用例检查，传参%s" % (data))
        resultAll = method().JOBcheckCaseAll(data)
        response = getResonCode().getSuccess()
        response["data"] = resultAll["data"]
        response["reuslt"] = resultAll["reuslt"]
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)

@csrf_exempt
@api_view(['POST'])
def getTestDB(request):  # 获取库的选择
    try:
        testdb = DolphinTestDatabase.objects.all()
        list = []
        data = testdb.values_list("id", "host")
        response = getResonCode().getSuccess()
        for i in range(len(data)):
            dictlist = {}
            dictlist["id"] = data[i][0]
            dictlist["host"] = data[i][1]
            list.append(dictlist)
        response["data"] = list
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)
        return None


@csrf_exempt
@api_view(['POST'])
def getTestSQL(request):  # 获取SQL结果数据
    data = json.loads(request.body)
    try:
        result = method().getSQLValue(id=data["id"], sql=data["sql"], SQLMomentum=data["SQLMomentum"],
                                      reusltList=data["reusltList"])

        response = getResonCode().getSuccess()
        response["data"] = result
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)
        return None


@csrf_exempt
@api_view(['POST'])
def getHerders(request):  # 获取herder表
    try:
        herdersList = json.loads(serializers.serialize("json", DolphinTestHeards.objects.all()))
        response = getResonCode().getSuccess()
        response["herdersList"] = herdersList
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)


@csrf_exempt
@api_view(['POST'])
def AssertionCase(request):  # 断言数据
    data = json.loads(request.body)
    try:
        Result = method().AssertionResults(request_result=data["request_result"], result=data["finalResult"],
                                           reusltlist=data["FinalValueResult"], sqldata=data["sqldata"])
        response = getResonCode().getSuccess()
        response["data"] = Result
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)


@csrf_exempt
@api_view(['POST'])
def executionCase(request):  # 执行接口
    data = json.loads(request.body)
    print(data)
    try:
        Result = ExecutionCase().singleeExecution(data["caseList"])
        response = getResonCode().getSuccess()
        response["data"] = Result
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)


@csrf_exempt
@api_view(['POST'])
def copyCase(request):  # 复制当前接口内容
    data = eval(json.loads(request.body)["data"])
    try:
        caseOld = DolphinTestRequestTestCase.objects.get(case_id=data["id"])
        caseOld.case_id = None
        caseOld.save()
        response = getResonCode().getSuccess()
        response["data"] = data
        return JsonResponse(response)
    except EOFError as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)
